import upng from '../../node_modules/upng-js/UPNG'

function formatNumber(n) {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}

export function formatTime(date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  const t1 = [year, month, day].map(formatNumber).join('/')
  const t2 = [hour, minute, second].map(formatNumber).join(':')

  return `${t1} ${t2}`
}

function getdate(time , k) { // 获取当前日期
  let d ;
  d = new Date(time) || new Date();
  if (k == 1) {
    return (d.getFullYear() + 1) + '-' + (d.getMonth() + 1) + '-' + d.getDate();
  }else if( k == 'dateTime' || k == 'monthTime'){

    let s = d.getFullYear() ,
      month = ( '0' + (d.getMonth()+1) ).slice(-2) ,
      day = ( '0' + d.getDate() ).slice(-2) ,
      hour = ( '0' + d.getHours()).slice(-2) ,
      second = ( '0' + d.getSeconds() ).slice(-2) ,
      m = ( '0' + d.getMinutes() ).slice(-2);

    // s = s + '-' + month + '-' + day + ' ' + hour + ':' + second ;
    m = month + '-' + day + ' ' + hour + ':' + m ;
    s = s + '-' + m ;

    if( k == 'dateTime'){
      return s;
    }else{
      return m
    }

  } else {
    let s = d.getFullYear();
    if ((d.getMonth() ) >= 10) {
      s = s + '-' + (d.getMonth() );
    } else {
      s = s + '-0' + (d.getMonth() );
    }
    if ((d.getDate() + 1) >= 10) {
      s = s + '-' + (d.getDate());
    } else {
      s = s + '-0' + (d.getDate());
    }
    return s;
  }

}

/* 小程序选择图片 */
function chooseImage(methods) {
  return new Promise((resolve, reject) => {
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        /* console.log(res);
         console.log(res.tempFiles);*/
        let types = res.tempFilePaths[0].split('.') ,
          type = types[types.length-1] ,
          all_type = ['jpg','png','jpeg','PNG','JPG','JPEG'];
        if(all_type.indexOf(type) < 0){
          wx.showToast({
            title: '请选择jpg/jpeg/png格式的图片！',
            icon: 'none'
          });
          reject('err');
          return
        }

        if (methods == 'files') {
          resolve(res.tempFiles)
        } else {
          resolve(res.tempFilePaths)
        }
      },
      fail: function (err) {

        if (err.errMsg != 'chooseImage:fail cancel') {
          wx.showToast({
            title: '获取图片失败',
            icon: 'none'
          })
          resolve('err')
        }
      }
    })
  })
}

export function Tobase64(imgPath, h, w) {

  return new Promise((resolve, reject) => {

    let canvas = wx.createCanvasContext('Canvas'),
      v = this;
    canvas.drawImage(imgPath, 0, 0, w, h);

    canvas.draw(false, () => {

      wx.canvasGetImageData({
        canvasId: 'Canvas',
        x: 0,
        y: 0,
        width: w,
        height: h,
        success(res) {
          /*   if (platform === 'ios') {
                 // 兼容处理：ios获取的图片上下颠倒
                 res = v.reverseImgData(res)
             }*/
          let pngData = upng.encode([res.data.buffer], res.width, res.height)
          let base64 = wx.arrayBufferToBase64(pngData)
          resolve('data:image/jpeg;base64,' + base64)
        },
        fail(err) {
          reject(err)
        }
      })
    })
  })
}

export function  getImginfo(path) {
  return new Promise((resolve, reject) => {
    wx.getImageInfo({
      src: path,
      success(data) {
        resolve(data)
      },
      fail(res) {
        console.log(err)
      }
    })
  })
}

export function reverseImgData(res) {//IOS拍照转向
  var w = res.width
  var h = res.height
  let con = 0
  for (var i = 0; i < h / 2; i++) {
    for (var j = 0; j < w * 4; j++) {
      con = res.data[i * w * 4 + j]
      res.data[i * w * 4 + j] = res.data[(h - i - 1) * w * 4 + j]
      res.data[(h - i - 1) * w * 4 + j] = con
    }
  }
  return res
}

export function getlocation(mc) {
  return new Promise((resolve, reject) => {
    mc.getCenterLocation({
      success: function (res) {
        resolve(res)
        // console.log(res.longitude)
        // console.log(res.latitude)
      }
      // wx.getLocation({
      //   type: 'gcj02', // 返回可以用于wx.openLocation的经纬度
      //   success: function (res) {
      //     resolve(res)
      //     // var latitude = res.latitude//维度
      //     // var longitude = res.longitude//经度
      //     // console.log(res);
      //     // that.loadCity(latitude,longitude);
      //   }
    })
  })
}

export function compareVersion(v1,v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  const len = Math.max(v1.length, v2.length)

  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i])
    const num2 = parseInt(v2[i])

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }

  return 0
}


export function DeviceOrientation(cb){//获取手机旋转方向
  let v = this ;
  wx.onAccelerometerChange(function(res) {

    let _x = judgeSign(res.x) ,
      _y = judgeSign(res.y) ,
      _z = judgeSign(res.z) ,
      _direction = '' ;
    /*   console.log('x --- ', res.x , _x) ;
       console.log('y --- ', res.y , _y) ;
       console.log('z --- ', res.z , _z) ;*/
    if(_z === 'minus' && _x === 'plus' && _y === 'plus'){
      _direction = 'minus';
    }else{
      _direction = 'plus';
    }

    cb(_direction)

  })
}

function judgeSign(num) {
  var reg = new RegExp("^-?[0-9]*.?[0-9]*$");
  if ( reg.test(num) ) {
    var absVal = Math.abs(num);
    return num==absVal?'plus':'minus';
  }
  else {
    return 'not';
  }
}

function checkPhone(str) {
  if(!(/^1[3456789]\d{9}$/.test(str))){
    return false;
  }else{
    return true
  }
}

function MakePhone(phone) {//打电话
  if(phone){
    wx.makePhoneCall({
      phoneNumber: phone,
    })
  }else{
    wx.showToast({
      title: '还没有添加电话呢！',
      duration: 2000,
      icon: 'none'
    });
  }
}

function AddWX(wx) {
  if(wx){
    wx.setClipboardData({
      data: wx,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功'
            })
          }
        })
      }
    })
  }else{
    wx.showToast({
      title: '还没有添加微信呢！',
      duration: 2000,
      icon: 'none'
    });
  }

  return true

}

export function clearLoginInfo() {
  wx.removeStorageSync('loginMsg');
  wx.removeStorageSync('token');
}

export function dateFormat(str) {
  var year = new Date(str).getFullYear();
  var month = new Date(str).getMonth()+1;
  var day = new Date(str).getDate();
  var  h=(new Date(str).getHours()-10)<0?"0"+new Date(str).getHours():new Date(str).getHours();
  var  m=(new Date(str).getMinutes()-10)<0?"0"+new Date(str).getMinutes():new Date(str).getMinutes();
  var  s=(new Date(str).getSeconds()-10)<0?"0"+new Date(str).getSeconds():new Date(str).getSeconds();

  var newDate=new Date();
  var year1=newDate.getFullYear();
  var month1=newDate.getMonth()+1;
  var day1=newDate.getDate();

  if(year==year1&&month==month1&&day==day1){
    return  h+":"+m
  }
  else if(year==year1&&month==month1&&day+1==day1){
    return "昨天"
  }
  else if(year!=year1||month!=month1||day+1!=day1){
    return  month+"月"+day+"日"
  }
}

export function Base64() {

  // private property
  let _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

  // public method for encoding
  this.encode = function (input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;
    input = _utf8_encode(input);
    while (i < input.length) {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);
      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;
      if (isNaN(chr2)) {
        enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
        enc4 = 64;
      }
      output = output +
        _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
        _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
    }
    return output;
  }

  // public method for decoding
  this.decode = function (input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    while (i < input.length) {
      enc1 = _keyStr.indexOf(input.charAt(i++));
      enc2 = _keyStr.indexOf(input.charAt(i++));
      enc3 = _keyStr.indexOf(input.charAt(i++));
      enc4 = _keyStr.indexOf(input.charAt(i++));
      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;
      output = output + String.fromCharCode(chr1);
      if (enc3 != 64) {
        output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
        output = output + String.fromCharCode(chr3);
      }
    }
    output = _utf8_decode(output);
    return output;
  }

  // private method for UTF-8 encoding
  let _utf8_encode = function (string) {
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";
    for (var n = 0; n < string.length; n++) {
      var c = string.charCodeAt(n);
      if (c < 128) {
        utftext += String.fromCharCode(c);
      } else if((c > 127) && (c < 2048)) {
        utftext += String.fromCharCode((c >> 6) | 192);
        utftext += String.fromCharCode((c & 63) | 128);
      } else {
        utftext += String.fromCharCode((c >> 12) | 224);
        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
        utftext += String.fromCharCode((c & 63) | 128);
      }

    }
    return utftext;
  }

  // private method for UTF-8 decoding
  let _utf8_decode = function (utftext) {
    var string = "";
    var i = 0;
    var c = 0;
    var c1 = 0;
    var c2 = 0;
    var c3 = 0;
    while ( i < utftext.length ) {
      c = utftext.charCodeAt(i);
      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      } else if((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i+1);
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        i += 2;
      } else {
        c2 = utftext.charCodeAt(i+1);
        c3 = utftext.charCodeAt(i+2);
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        i += 3;
      }
    }
    return string;
  }
}


/**
 * 过滤 emoji表情
 * @param name
 * @returns {void|*|string|never}
 */
function filterEmoji(name){

  var str = name.replace(/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/ig, "");

  return str;

}


export default {
  clearLoginInfo,
  formatNumber,
  formatTime,
  getdate,
  chooseImage,
  getImginfo,
  Tobase64,
  getlocation,
  compareVersion,
  DeviceOrientation,
  checkPhone,
  MakePhone,
  dateFormat,
  AddWX,
  Base64,
  filterEmoji
}
